<template>
    <div class="container">
        <el-row :gutter="12">
            <splitpanes class="default-theme">
                <pane min-size="4" size="12">
                    <el-col class="tenant-left-tree">
                        <TenantTree ref="tenantTreeRef" :data="state.tree.data" @treeSarch="treeSarch"></TenantTree>
                    </el-col>
                </pane>
                <pane size="88">
                    <el-col>
                        <div class="search-main">
                            <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="68px">
                                <el-form-item label="租户账号" prop="loginName">
                                    <el-input v-model="queryParams.loginName" placeholder="请输入租户账号" clearable
                                        style="width: 200px" @keyup.enter="handleQuery" />
                                </el-form-item>
                                <el-form-item label="租户名称" prop="userName">
                                    <el-input v-model="queryParams.userName" placeholder="请输入租户名称" clearable
                                        style="width: 200px" @keyup.enter="handleQuery" />
                                </el-form-item>
                                <el-form-item label="电话" prop="iphone">
                                    <el-input v-model="queryParams.iphone" placeholder="请输入电话" clearable
                                        style="width: 200px" @keyup.enter="handleQuery" />
                                </el-form-item>
                                <el-form-item>
                                    <el-button type="primary" icon="Search" @click="handleQuery" size="">搜索</el-button>
                                    <el-button icon="Refresh" @click="resetQuery" size="">重置</el-button>
                                </el-form-item>
                            </el-form>
                        </div>

                        <el-row class="toolbar-row">
                            <el-col :span="24">
                                <el-button type="primary" plain icon="Plus" @click="state.dialogVisible = true"
                                    size="">新增</el-button>
                            </el-col>
                        </el-row>

                        <vxe-grid v-bind="gridOptions" v-on="gridEvents" ref="gridRef">

                            <template #edit_iuse="{ row }">
                                <el-switch v-model="row.iuse" :active-value="1" :inactive-value="0"></el-switch>
                            </template>
                            
                            <template #iuse="{ row }">
                                <el-tag :type="row.iuse ? 'primary' : 'danger'" :disable-transitions="true">{{ row.iuse ?
                                    '正常' : '停用' }}</el-tag>
                            </template>


                            <template #action="{ row }">
                                <template v-if="hasEditStatus(row)">
                                    <el-button type="primary" @click="saveRowEvent(row)" size="">保存</el-button>
                                    <el-button @click="cancelRowEvent()" size="">取消</el-button>
                                </template>
                                <template v-else>
                                    <el-button type="primary" @click="editRowEvent(row)" size="" plain>编辑</el-button>
                                    <el-popconfirm title="确实要删除当前项吗?" @confirm="deleteRow(row)">
                                        <template #reference>
                                            <el-button type="primary" @click="" size="" plain
                                                color="#ff4444f7">删除</el-button>
                                        </template>
                                    </el-popconfirm>
                                </template>
                            </template>
                        </vxe-grid>
                    </el-col>
                </pane>
            </splitpanes>
        </el-row>

        <!-- 添加或修改岗位对话框 -->
        <el-dialog title="新增用户" v-model="state.dialogVisible" width="500" append-to-body :close-on-click-modal="false">
            <el-form ref="postRef" :model="userForm" :rules="rules" label-width="100">
                <el-form-item label="租户：" prop="tenantId" class="dislog-label-item">
                    <el-tree-select v-model="userForm.tenantId" :data="state.tree.data"
                        :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="选择租户"
                        check-strictly />
                </el-form-item>
                <el-form-item label="用户账号：" prop="loginName" class="dislog-label-item">
                    <el-input v-model="userForm.loginName" placeholder="请输入用户账号" />
                </el-form-item>
                <el-form-item label="用户名称：" prop="userName" class="dislog-label-item">
                    <el-input v-model="userForm.userName" placeholder="请输入用户名称" />
                </el-form-item>
                <el-form-item label="电话：" prop="iphone" class="dislog-label-item">
                    <el-input type="number" v-model="userForm.iphone" controls-position="right" :min="0"
                        placeholder="请输入电话" />
                </el-form-item>
                <el-form-item label="邮件地址：" prop="email" class="dislog-label-item">
                    <el-input v-model="userForm.email" placeholder="请输入邮件地址" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="SystemUser">
import { reactive, ref, toRefs, onMounted, watch, defineAsyncComponent } from "vue";
import * as TenantApi from "@/api/TenantApi";
import { ElMessage } from "element-plus";
import { userSearch, userSave, userDel } from "@/api/systemApi";
import { Splitpanes, Pane } from "splitpanes";
import 'splitpanes/dist/splitpanes.css';
import { DEFAULT_ID } from '@/utils/constants';


const TenantTree = defineAsyncComponent(() => import('@/components/tree/CustomTree.vue'));
const gridRef = ref();
const queryRef = ref(null);
const deptTreeRef = ref(null);
const tenantTreeRef = ref('');
const { log } = console;

//组件状态
const state = reactive({
    dialogVisible: false,
    userForm: {
        tenantId: null,
    },
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: null,
        iphone: null,
        loginName: null,
        tenantId: null,
    },
    tree: {
        data: [],
        tenantName: '',
    }
});

//行内编辑
const regionEditRender = reactive({
    name: 'VxeTreeSelect',
    options: null,
    optionProps: {
        value: 'id', label: 'label', children: 'children'
    }
})
const { queryParams, userForm } = toRefs(state);


function treeSarch(data) {
    if (data.id == DEFAULT_ID) {
        return;
    }
    queryParams.value.tenantId = data.id;
    handleQuery();
}

//add用户
async function submitForm() {
    log(userForm.value)
    let res = await userSave(userForm.value);
    if (res.code == 200 && res.data) {
        ElMessage.success("操作成功");
        handleQuery();
    }
    state.dialogVisible = false;
}

function cancel() {
    state.dialogVisible = false;
}



//表格配置
const gridOptions = reactive({
    emptyText: "暂无数据！",
    keepSource: true,
    headerRowClassName: "table-head-cla",
    border: true,
    showOverflow: true,
    loading: false,
    align: "center",
    rowConfig: {
        isCurrent: true,
        isHover: true,
    },
    size: "small",
    autoResize: true,
    columnConfig: {
        isHover: true,
        resizable: false,
    },
    editConfig: {
        showIcon: false, //是否显示列头编辑图标
        trigger: "manual",
        showStatus: true,
        autoClear: true,
        mode: "row",
    },
    pagerConfig: {
        border: true,
        enabled: true,
        total: 0,
        currentPage: 1,
        pageSize: 10,
        total: 0,
        layouts: [
            "Home",
            "PrevJump",
            "PrevPage",
            "Number",
            "NextPage",
            "NextJump",
            "End",
            "Sizes",
            "FullJump",
            "Total",
        ],
    },
    columns: [
        { type: "seq", width: 70 },
        { field: "tenantId", title: "租户", editRender: regionEditRender },
        {
            field: "loginName",
            title: "用户账号",
            sortable: true,
            editRender: { name: "VxeInput" },
        },
        {
            field: "userName",
            title: "用户名称",
            sortable: true,
            editRender: { name: "VxeInput" },
        },
        {
            field: "iphone",
            title: "电话",
            sortable: true,
            editRender: { name: "VxeInput" },
        },
        {
            field: "email",
            title: "邮件地址",
            sortable: true,
            editRender: { name: "VxeInput" },
        },
        { field: "iuse", title: "状态", sortable: false, editRender: {}, slots: { default: 'iuse', edit: 'edit_iuse' } },
        { field: "createByUserName", title: "创建人" },
        { field: "createTime", title: "创建日期", sortable: true },
        { field: "updateByUserName", title: "修改人" },
        { field: "lastModifyTime", title: "修改日期", sortable: true },
        { title: "操作", slots: { default: "action" }, fixed: 'right', width: 160 },
    ],
    data: [],
});

//分页事件
const gridEvents = {
    pageChange({ pageSize, currentPage }) {
        gridOptions.pagerConfig.currentPage = currentPage;
        gridOptions.pagerConfig.pageSize = pageSize;
        queryParams.value.pageNum = currentPage;
        queryParams.value.pageSize = pageSize;
        handleQuery(queryParams);
    },
};


//查询list
async function handleQuery() {
    gridOptions.loading = true;
    let res = await userSearch(queryParams.value);
    gridOptions.data = res.data.records;
    gridOptions.pagerConfig.total = res.data.total
    gridOptions.loading = false;
}

function resetQuery() {
    queryRef.value.resetFields();
    queryParams.value.tenantId = null;
    tenantTreeRef.value.resetTree();
    handleQuery();
}

const hasEditStatus = (row) => {
    const $grid = gridRef.value;
    if ($grid) {
        return $grid.isEditByRow(row);
    }
};

const editRowEvent = (row) => {
    const $grid = gridRef.value;
    if ($grid) {
        $grid.setEditRow(row);
    }
};

//编辑用户
const saveRowEvent = async (row) => {
    const $grid = gridRef.value
    if ($grid) {
        $grid.clearEdit().then(async () => {
            let res = await userSave(row);
            if (res.code == 200 && res.data) {
                ElMessage.success("操作成功");
                handleQuery();
            }

        })
    }

};

//编辑取消
const cancelRowEvent = (row) => {
    const $grid = gridRef.value;
    if ($grid) {
        $grid.clearEdit().then(() => {
            // 还原行数据
            $grid.revertData(row);
        });
    }
};

//删除数据
async function deleteRow(row) {
    let res = await userDel(row.id);
    if (res.code == 200 && res.data) {
        ElMessage.success("操作成功");
        handleQuery();
    }
}


/** 查询租户树结构 */
async function getTenantTree() {
    state.tree.data = [];
    const res = await TenantApi.tenantTree();
    const tree = { id: DEFAULT_ID, label: "苏信科技", children: [], disabled: true };
    if (res.code == 200 && res.data.length > 0) {
        tree.children = res.data
        state.tree.data.push(tree);
        regionEditRender.options = res.data;
    }

};


/** 根据名称筛选部门树 */
watch(() => state.tree.tenantName, val => {
    deptTreeRef.value.filter(val);
});

onMounted(() => {
    handleQuery();
    getTenantTree();
});


</script>

<style scoped lang="scss">
.container {

    .splitpanes__pane .tenant-left-tree {
        padding-right: var(--tenant-tree-margin) !important;
    }

    .tree-header {
        line-height: 78px;
    }


    .search-main {
        line-height: 78px;

        .el-form-item {
            margin-bottom: 0px;
        }
    }

    .toolbar-row.el-row {
        margin-bottom: 10px;
    }
}
</style>
